package com.sunshine.ssm.pool;

import org.apache.commons.pool2.impl.GenericObjectPool;

/**
 * @author WeiHong
 * @date 2019/1/11
 */
public class PoolTest {


    public static void main(String[] args) throws Exception {
        borrowObject(2);
    }


    public static void borrowObject(int counts) throws Exception {
        long begin = System.currentTimeMillis();
        PoolConfig poolConfig = new PoolConfig();
        poolConfig.setMaxTotal(2);
        poolConfig.setMaxWaitMillis(1000);
        poolConfig.setTestOnCreate(true);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        // new 一个对象池。
        GenericObjectPool<Person> personPool = new GenericObjectPool<>(new PersonFactory(), poolConfig);
        for (int i = 0; i < counts; i++) {
            Person person = personPool.borrowObject();
            person.work();
            personPool.returnObject(person);
        }
        Thread.sleep(3000);
        long end = System.currentTimeMillis();
        showUseTime(begin, end);

    }

    public static void createBoject(int counts) {
        long begin = System.currentTimeMillis();
        for (int i = 0; i < counts; i++) {
            PersonFactory personFactory = new PersonFactory();
            Person person = personFactory.create();
            person.work();
        }
        long end = System.currentTimeMillis();
        showUseTime(begin, end);
    }


    public static void showUseTime(long begin, long end) {
        long l = (end - begin) / 1000;
        System.out.println("总共耗时： " + l + "秒");
    }

}
